package com.heiyanquan.security.core.validate.image;

import com.heiyanquan.security.core.properties.SecurityProperties;
import com.heiyanquan.security.core.validate.ValidateCodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author dingaolin
 * @Date: 2017/12/9 0009.
 */
public class ImageCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public ImageCode generate(ServletWebRequest request) {
        int width = ServletRequestUtils.getIntParameter(request.getRequest(), "width", securityProperties.getValidateCodeProperties().getImageCodeProperties().getWidth());
        int height = ServletRequestUtils.getIntParameter(request.getRequest(), "height", securityProperties.getValidateCodeProperties().getImageCodeProperties().getHeight());
        int length = securityProperties.getValidateCodeProperties().getImageCodeProperties().getLength();
        int expiredIn = securityProperties.getValidateCodeProperties().getImageCodeProperties().getExpiredIn();

        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = bi.getGraphics();
        Color c = new Color(250, 150, 255);
        g.setColor(c);
        g.fillRect(0, 0, 68, 22);
        //验证码字符集合
        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        Random r = new Random();
        int len = ch.length;
        int index;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; ++i) {
            index = r.nextInt(len);
            //设置验证码字符随机颜色
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            //画出对应随机的验证码字符
            g.drawString(ch[index] + "", (i * 15) + 3, 18);
            sb.append(ch[index]);
        }
        return new ImageCode(bi, sb.toString(), expiredIn);
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
